//
//  CloudFileViewController.swift
//  AutoPrint
//
//  Created by 胡玉葱 on 16/10/23.
//  Copyright © 2016年 fatcat. All rights reserved.
//

import UIKit

class CloudFileViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIAlertViewDelegate {

    let CACHES_PATH = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).first!
    let ASK_BEFORE_SHARE_ALERT_ID = 101
    
    var tableView:UITableView!
    var listItems:NSMutableArray!
    
    var editButton: UIBarButtonItem! // 多选按钮
    var multiConfirmBtn: UIBarButtonItem! // 确认上传按钮
    
    var refreshControl:UDRefreshControl! // 上方 下拉刷新
    var refreshPageControl: UDRefreshControl! // 下方 上拉加载更多
    var currentPage = 0 // 当前页 读取完数据就变1
    var pageLoadable = false // 是否可以加载更多
    
    var spinner:UIView! // 加载菊花
    
    var fileToperate: NSDictionary?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //UIAlertView(title: nil, message: "如果要在这里选择文件打印，需要每个文件的fileMD5来调用秒传接口", delegate: nil, cancelButtonTitle: "OK").show()
        
        listItems = NSMutableArray()
        
        
        
        title = "我的云端文件"
        // 下一个视图的返回键将显示 返回
        let backItem = UIBarButtonItem()
        backItem.title = "返回"
        navigationItem.backBarButtonItem = backItem
        
        // 多选切换按钮
        //editButton = UIBarButtonItem(title: "多选", style: .Plain, target: self, action: #selector(FirstViewController.multiSelect(_:)))
        //navigationItem.rightBarButtonItem = editButton
        
        // 上传按钮
        multiConfirmBtn = UIBarButtonItem(title: "上传", style: .Plain, target: self, action: #selector(FirstViewController.multiSubmit))
        
        tableView = UITableView(frame: view.frame, style: .Grouped)
        view.addSubview(tableView)
        tableView.tintColor = Fatcat.SELECTED_COLOR
        
        // 下拉刷新提示器
        refreshControl = UDRefreshControl(frame: CGRect(x: 0, y: -64, width: view.bounds.width, height: 64))
        tableView.addSubview(refreshControl)
        
        // 上拉加载更多提示器
        refreshPageControl = UDRefreshControl(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 64))
        refreshPageControl.normalTitle = "没有更多了"
        
        
        // 读取本地数据
        if NSFileManager.defaultManager().fileExistsAtPath("\(CACHES_PATH)/myCloudFiles.plist") {
            listItems = NSMutableArray(contentsOfFile: "\(CACHES_PATH)/myCloudFiles.plist")
            currentPage = 1
            if listItems.count >= 10 { // 10条分一页
                self.refreshPageControl.normalTitle = "下拉载入更多"
                self.pageLoadable = true
            }else{
                self.refreshPageControl.normalTitle = "没有更多了"
                self.refreshPageControl.readyTitle = "没有更多了"
                self.pageLoadable = false
            }
        }
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.allowsSelection = false
        
        // 加载菊花
        spinner = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
        spinner.center = view.center
        spinner.backgroundColor = UIColor(white: 0, alpha: 0.75)
        spinner.layer.cornerRadius = 5
        view.addSubview(spinner)
        let actIndi = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
        actIndi.center = CGPoint(x: 25, y: 25)
        actIndi.activityIndicatorViewStyle = .White
        actIndi.startAnimating()
        spinner.addSubview(actIndi)
        spinner.alpha = 0
        
        let fakeNavBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 64))
        view.addSubview(fakeNavBar)
        fakeNavBar.barTintColor = Fatcat.THEME_COLOR
        fakeNavBar.barStyle = .Black
        fakeNavBar.tintColor = UIColor.whiteColor()
        let fakeNavItem = UINavigationItem(title: title!)
        let fakeBackButton = UIBarButtonItem()
        fakeBackButton.title = "    返回"
        fakeNavItem.leftBarButtonItem = fakeBackButton
        fakeNavItem.rightBarButtonItem = editButton
        fakeNavBar.pushNavigationItem(fakeNavItem, animated: false)
        
        
        refreshList()
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        navigationController?.navigationBar.hidden = false
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        // 下拉刷新准备刷新
        if tableView.contentOffset.y < -108 {
            
            if refreshControl.state == .Normal{
                refreshControl.readyToRefresh()
            }
            
        }else{
            // 松手刷新慢慢挪回去，取消刷新
            if refreshControl.state == .Ready{
                refreshControl.endRefresh()
            }
            
        }
        
        // 上拉，同理
        if pageLoadable {
            if tableView.contentOffset.y > tableView.contentSize.height - tableView.frame.height + 64{
                if refreshPageControl.state == .Normal{
                    refreshPageControl.readyToRefresh()
                }
                
            }else{
                if refreshPageControl.state == .Ready{
                    refreshPageControl.endRefresh()
                }
            }
        }
        
    }
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        // MARK: 下拉刷新出发
        if refreshControl.state == .Ready{
            
            refreshControl.beginRefresh()
            refreshList()
        }
        
        if refreshPageControl.state == .Ready{
            
            if pageLoadable {
                print("load more")
                refreshPageControl.beginRefresh()
                loadMore()
            }
            
        }
        
    }
    
    func refreshList(){
        spinner.alpha = 1
        refreshControl.beginRefresh()
        
        let resq = NSMutableURLRequest(URL: NSURL(string: "\(Fatcat.SERVER_DOMAIN_NAME)\(Fatcat.FILE_API)")!)
        resq.HTTPMethod = "POST"
        resq.HTTPBody = NSString(string: "act=personalFile&page=1").dataUsingEncoding(NSUTF8StringEncoding)
        
        NSURLSession.sharedSession().dataTaskWithRequest(resq) { (data:NSData?, resp:NSURLResponse?, err:NSError?) in
            dispatch_async(dispatch_get_main_queue(), { 
                self.spinner.alpha = 0
                self.refreshControl.endRefresh()
            })
            var failed = true
            if err == nil{
                if data != nil{
                    print(NSString(data: data!, encoding: NSUTF8StringEncoding))
                    let jsonObj = try? NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
                    if jsonObj != nil{
                        let jsonDic = jsonObj as? NSDictionary
                        if jsonDic != nil{
                            let jsonList = jsonDic?.objectForKey("data") as? NSArray
                            if jsonList != nil{
                                self.listItems = NSMutableArray(array: jsonList!)
                                self.currentPage = 1
                                failed = false
                                dispatch_async(dispatch_get_main_queue(), { 
                                    self.tableView.reloadData()
                                    if self.listItems.count >= 10 {
                                        self.refreshPageControl.normalTitle = "下拉载入更多"
                                        self.refreshPageControl.readyTitle = "松开刷新"
                                        self.pageLoadable = true
                                    }else{
                                        self.refreshPageControl.normalTitle = "没有更多了"
                                        self.refreshPageControl.readyTitle = "没有更多了"
                                        self.pageLoadable = false
                                    }

                                    
                                })
                                self.listItems.writeToFile("\(self.CACHES_PATH)/myCloudFiles.plist", atomically: true)
                                
                            }
                        }
                    }
                }
            }
            if failed{
                dispatch_async(dispatch_get_main_queue(), { 
                    UIAlertView(title: "获取失败", message: nil, delegate: nil, cancelButtonTitle: "OK").show()
                })
            }
        }.resume()
    }
    
    func loadMore(){
        spinner.alpha = 1
        refreshControl.beginRefresh()
        refreshPageControl.beginRefresh()
        
        let resq = NSMutableURLRequest(URL: NSURL(string: "\(Fatcat.SERVER_DOMAIN_NAME)\(Fatcat.FILE_API)")!)
        resq.HTTPMethod = "POST"
        resq.HTTPBody = NSString(string: "act=personalFile&page=\(currentPage+1)").dataUsingEncoding(NSUTF8StringEncoding)
        
        NSURLSession.sharedSession().dataTaskWithRequest(resq) { (data:NSData?, resp:NSURLResponse?, err:NSError?) in
            dispatch_async(dispatch_get_main_queue(), {
                self.spinner.alpha = 0
                self.refreshControl.endRefresh()
                self.refreshPageControl.endRefresh()
            })
            var failed = true
            if err == nil{
                if data != nil{
                    print(NSString(data: data!, encoding: NSUTF8StringEncoding))
                    let jsonObj = try? NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
                    if jsonObj != nil{
                        let jsonDic = jsonObj as? NSDictionary
                        if jsonDic != nil{
                            let jsonList = jsonDic?.objectForKey("data") as? NSArray
                            if jsonList != nil{
                                self.listItems.addObjectsFromArray(jsonList as! [AnyObject])
                                self.currentPage += 1
                                failed = false
                                dispatch_async(dispatch_get_main_queue(), {
                                    self.tableView.reloadData()
                                    if self.listItems.count >= 10 {
                                        self.refreshPageControl.normalTitle = "下拉载入更多"
                                        self.refreshPageControl.readyTitle = "松开刷新"
                                        self.pageLoadable = true
                                    }else{
                                        self.refreshPageControl.normalTitle = "没有更多了"
                                        self.refreshPageControl.readyTitle = "没有更多了"
                                        self.pageLoadable = false
                                    }
                                    
                                    
                                })
                                self.listItems.writeToFile("\(self.CACHES_PATH)/myCloudFiles.plist", atomically: true)
                                
                            }
                        }
                    }
                }
            }
            if failed{
                dispatch_async(dispatch_get_main_queue(), {
                    UIAlertView(title: "获取失败", message: nil, delegate: nil, cancelButtonTitle: "OK").show()
                })
            }
            }.resume()
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listItems.count
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 64
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .Default, reuseIdentifier: "file")
        var indent: CGFloat = 0.0
        if tableView.editing {
            indent = 36
        }
        let thisFileItem = listItems.objectAtIndex(indexPath.row) as! NSDictionary
        let icon = UIImageView(frame: CGRect(x: indent + 16, y: 8, width: 48, height: 48))
        icon.contentMode = .Center
        icon.backgroundColor = UIColor.lightGrayColor()
        cell.addSubview(icon)
        
        let nameLabel = UILabel(frame: CGRect(x: indent + 72, y: 8, width: view.bounds.width - 80, height: 20))
        
        cell.addSubview(nameLabel)
        
        let subLabel = UILabel(frame: CGRect(x: indent + 72, y: 36, width: view.bounds.width - 80, height: 20))
        
        subLabel.textColor = UIColor.lightGrayColor()
        cell.addSubview(subLabel)
        
        let fileName = thisFileItem.objectForKey("sourceFileName") as? String
        nameLabel.text = fileName
        subLabel.text = UDDate.softTime(thisFileItem.objectForKey("addTime") as! String)
        
        // MARK: 文件图标
        if fileName != nil {
            let fileType = fileName!.componentsSeparatedByString(".").last
            if fileType != nil {
                if fileType == "doc" || fileType == "docx" {
                    icon.backgroundColor = UIColor.clearColor()
                    icon.image = UIImage(named: "documents_icon_doc")
                }else if fileType == "xls" || fileType == "xlsx" {
                    icon.backgroundColor = UIColor.clearColor()
                    icon.image = UIImage(named: "documents_icon_xls")
                }else if fileType == "ppt" || fileType == "pptx" {
                    icon.backgroundColor = UIColor.clearColor()
                    icon.image = UIImage(named: "documents_icon_ppt")
                }else if fileType == "pdf"{
                    icon.backgroundColor = UIColor.clearColor()
                    icon.image = UIImage(named: "documents_icon_pdf")
                }else if fileType == "txt"{
                    icon.backgroundColor = UIColor.clearColor()
                    icon.image = UIImage(named: "documents_icon_txt")
                }
            }
        }
        return cell
    }
    func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if section == 0{
            let footer = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 64))
            footer.addSubview(refreshPageControl)
            return footer
        }
        return nil
    }
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        if !tableView.editing {
            tableView.deselectRowAtIndexPath(indexPath, animated: true)
            hidesBottomBarWhenPushed = true
            let thisRowItem = listItems.objectAtIndex(indexPath.row) as! NSDictionary
            let filePath = thisRowItem.objectForKey("filePath") as! String
            let fileName = thisRowItem.objectForKey("sourceFileName") as! String
            let fileMD5 = thisRowItem.objectForKey("fileMd5") as! String
            //TODO: md5 undefined key
            navigationController?.pushViewController(FileOLPreViewController(name: fileName, path: filePath, md5: fileMD5), animated: true)
        }
    }
    func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true
    }
    
    func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
        if tableView.editing{
            return UITableViewCellEditingStyle(rawValue: UITableViewCellEditingStyle.Delete.rawValue | UITableViewCellEditingStyle.Insert.rawValue)!
        }
        return .Delete
        
    }
    
    func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
//        let deleteBtn = UITableViewRowAction(style: .Default, title: "删除") { (act:UITableViewRowAction, indexPath:NSIndexPath) in
//            print("delete")
//        }
        let thisRowItem = self.listItems.objectAtIndex(indexPath.row) as! NSDictionary
        var isShare = thisRowItem.objectForKey("isShare") as? String
        if isShare == nil{
            let isShareInt = thisRowItem.objectForKey("id") as? Int
            if isShareInt != nil{
                isShare = String(isShareInt!)
            }else{
                return nil
            }
            
        }
        var shareLabel = "分享"
        if isShare == "1" {
            shareLabel = "取消分享"
        }
        let shareBtn = UITableViewRowAction(style: .Normal, title: shareLabel) { (act:UITableViewRowAction, indexPath:NSIndexPath) in
            print("toggle share")
            // MARK: 调用文件共享接口
            
            if isShare == "0"{
                self.fileToperate = thisRowItem
                let alert = UIAlertView(title: "共享文件", message: "请勿共享个人资料相关的文件", delegate: self, cancelButtonTitle: "取消")
                alert.addButtonWithTitle("共享")
                alert.tag = self.ASK_BEFORE_SHARE_ALERT_ID
                alert.show()
                
            }else{
                self.toggleFileShare(thisRowItem)
            }
            
        }
//        return [deleteBtn, shareBtn]
        return [shareBtn]
    }

    func toggleFileShare(fileItem: NSDictionary){
        var fileID = fileItem.objectForKey("id") as? String
        if fileID == nil{
            let fileIDInt = fileItem.objectForKey("id") as? Int
            if fileIDInt != nil{
                fileID = String(fileIDInt!)
            }else{
                return
            }
            
        }
        let resq = NSMutableURLRequest(URL: NSURL(string: "\(Fatcat.SERVER_DOMAIN_NAME)\(Fatcat.FILE_API)")!)
        resq.HTTPMethod = "POST"
        resq.HTTPBody = NSString(string: "act=fileShare&id=\(fileID!)").dataUsingEncoding(NSUTF8StringEncoding)
        self.spinner.alpha = 1
        NSURLSession.sharedSession().dataTaskWithRequest(resq, completionHandler: { (data:NSData?, resp:NSURLResponse?, err:NSError?) in
            dispatch_async(dispatch_get_main_queue(), {
                self.spinner.alpha = 0
            })
            var failed = true
            if err == nil{
                if data != nil{
                    print(NSString(data: data!, encoding: NSUTF8StringEncoding))
                    let jsonObj = try? NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
                    if jsonObj != nil{
                        let jsonDic = jsonObj as? NSDictionary
                        if jsonDic != nil{
                            let reCode = jsonDic?.objectForKey("code") as! Int
                            if reCode == 200{
                                failed = false
                                dispatch_async(dispatch_get_main_queue(), {
                                    // TODO: 分享or取消分享？
                                    UIAlertView(title: "分享成功", message: nil, delegate: nil, cancelButtonTitle: "OK").show()
                                })
                            }
                        }
                    }
                }
            }
            if failed{
                dispatch_async(dispatch_get_main_queue(), {
                    UIAlertView(title: "操作失败", message: nil, delegate: nil, cancelButtonTitle: "OK").show()
                })
            }
        }).resume()
    }
    
    func multiSelect(sender: UIBarButtonItem){
        // MARK:多选按钮点击
        
        
        if tableView.editing {
            sender.title = "多选"
            navigationItem.leftBarButtonItem = nil
            navigationItem.rightBarButtonItem = sender
        }else{
            sender.title = "取消"
            navigationItem.leftBarButtonItem = sender
            navigationItem.rightBarButtonItem = multiConfirmBtn
        }
        tableView.setEditing(!tableView.editing, animated: true)
        tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: .None)
        
        
    }
    
    func multiSubmit(){
        //MARK: 在线文件多选直接上传
        if tableView.indexPathsForSelectedRows != nil{
            
            if NSUserDefaults.standardUserDefaults().objectForKey("user") == nil {
                presentViewController(UDLoginViewController(), animated: true, completion: nil)
                
            }else{
                var filesToUpload: [UDFile] = []
                for index in tableView.indexPathsForSelectedRows! {
                    let file = listItems.objectAtIndex(index.row) as! NSDictionary
                    let fileName = file.objectForKey("sourceFileName") as? String
                    let fileMD5 = file.objectForKey("fileMd5") as? String
                    //TODO: md5 undefined key
                    filesToUpload.append(UDFile(filePath: nil, fileName: fileName, fileSize: "在线文件", fileMD5: fileMD5))
                }
                hidesBottomBarWhenPushed = true
                navigationController?.pushViewController(FileReadyViewController(files: filesToUpload, step0VC: self), animated: true)
            }
            multiSelect(editButton)
        }else{
            UIAlertView(title: "请选择文件", message: nil, delegate: nil, cancelButtonTitle: "OK").show()
        }
        
    }
    
    func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
        if alertView.tag == ASK_BEFORE_SHARE_ALERT_ID{
            if buttonIndex == 1{
                if fileToperate != nil {
                    toggleFileShare(fileToperate!)
                }
                
            }
        }
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
